package com.changanw.middleware.rpc.config.spring.bean;

import com.changanw.middleware.rpc.config.ProviderConfig;
import com.changanw.middleware.rpc.domain.LocalServerInfo;
import com.changanw.middleware.rpc.domain.RpcProviderConfig;
import com.changanw.middleware.rpc.registry.RedisRegistryCenter;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 接口的注册过程其实并不复杂，只是把所有配置在 XML 文件中的接口信息依次发布到注册中心。
 * 这里的注册过程是把接口信息注册到 Redis，也就是调用 Redis 的 jedis.sadd(nozzle + "_" + alias, info) 写入接口信息。
 */
public class ProviderBean extends ProviderConfig implements ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(ProviderBean.class);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        RpcProviderConfig rpcProviderConfig = new RpcProviderConfig();
        rpcProviderConfig.setNozzle(nozzle);
        rpcProviderConfig.setRef(ref);
        rpcProviderConfig.setAlias(alias);
        rpcProviderConfig.setHost(LocalServerInfo.LOCAL_HOST);
        rpcProviderConfig.setPort(LocalServerInfo.LOCAL_PORT);

        //注册生产者
        long count = RedisRegistryCenter.registryProvider(nozzle, alias, JSON.toJSONString(rpcProviderConfig));

        logger.info("注册生产者：{} {} {}", nozzle, alias, count);
    }

}
